<?php
class UsersController extends AppController {
    var $name = 'Users';

    var $pageTitle = '';

    var $uses = array('User', 'UserHistory', 'UserIts', 'UserCustomer', 'UserSupplier', 'Customer', 'Site', 'CustProductSite', 'Supplier', 'UserCoH', 'Brand', 'CustomerSupplier');

    function beforeFilter() {
        parent::beforeFilter();

        //Configure AuthComponent
        $this->Session->delete('Auth.redirect');
        $this->Auth->autoRedirect = false;
        $this->Auth->allowedActions = array('index');
        $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'home');
        $this->set('parentNav', 'users');
    }

    function index() {
        $this->layout = 'default';
    }

    function login() {

        // บันทึกวันเวลา log in
        if ($this->Auth->user()) {
            $userHistory['UserHistory']['id'] = null;
            $userHistory['UserHistory']['user_id'] = $this->Auth->user('id');
            $userHistory['UserHistory']['log_in_time'] = date('Y-m-d H:i:s');
            $this->UserHistory->save($userHistory);

            if ($this->Auth->user('discontinued') == true) {
                // ล้างค่าที่อยู่ใน session ทั้งหมด
                $this->Session->destroy();
                $this->Session->setFlash("This user are no longer available");
                $this->redirect($this->Auth->logout());
            }

            // ดึง field จากตาราง User Type แต่ละประเภทมาไว้ที่ User
            $prefix = $this->Auth->user('prefix');
            if ($prefix == ITS_PREFIX) {
                $uI = $this->UserIts->findByUserId($this->Auth->user('id'));
                $this->_copyUserFields($uI, 'UserIts');
            } elseif ($prefix == CUST_PREFIX) {
                $uC = $this->UserCustomer->findByUserId($this->Auth->user('id'));
                $this->_copyUserFields($uC, 'UserCustomer');
                if ($this->Auth->user('is_head_user')) {
                    $this->Site->contain();
                    $site = $this->Site->find('first', array('conditions' => array('customer_id' => $this->Auth->user('customer_id'))));
                    $this->Session->write('Auth.User.site_id', $site['Site']['id']);
                }
            } elseif ($prefix == SUPPLIER_PREFIX) {
                $uS = $this->UserSupplier->findByUserId($this->Auth->user('id'));
                $this->_copyUserFields($uS, 'UserSupplier');
            }
            $this->redirect($this->Auth->redirect());
        } else {
            $this->redirect('index');
        }
    }

    /**
     * ตาราง User type มี 3 ตาราง คือ
     * UserIts, UserCustomer, UserSupplier
     * แต่ละตารางเก็บ Priviledge ที่ user แต่ละประเภทมี
     * method นี้ คัดลอก field ใน user type มาไว้ที่ Session User
     * เพื่อให้เรียกใช้งานได้ง่ายขึ้นและ backward compatiblity กับ code เก่า
     * @param array $u
     * @param string $model ชื่อ Model User type
     */
    function _copyUserFields($u, $model) {
        foreach($u[$model] as $k => $v) {
            // ไม่เอา field id กับ user_id ใน ตาราง user type มาใส่
            if ($k != 'id' && $k != 'user_id') {
                $this->Session->write("Auth.User.{$k}", $v);
            }
        }
    }

    function logout() {
        // บันทึกวันเวลา log out
        $this->UserHistory->id = $this->UserHistory->field('id', array('user_id' => $this->Auth->user('id')), 'log_in_time DESC');
        $this->UserHistory->saveField('log_out_time', date('Y-m-d H:i:s'));

        // ล้างค่าที่อยู่ใน session ทั้งหมด
        $this->Session->destroy();

        $this->redirect($this->Auth->logout());
    }

    function profile($id) {
        $this->pageTitle = 'User Profile';
        $this->data = $this->User->findById($id);
    }

    function history_display($user_id = null) {
        // ถ้ากดปุ่ม refresh
        if (isset($this->passedArgs['refresh'])) {
            $this->Session->delete($this->name);
        }

        if ($user_id == null) {
            $user_id = $this->data['UserHistory']['user_id'];
        }
        $this->paginate['UserHistory']['conditions'] = array('user_id' => $user_id);
        parent::display('UserHistory');
        $this->_paging('UserHistory', 'LIKE');
        $this->set('user_id', $user_id);
        $this->render('history_display');
    }

    /**
     * หน้าแรกหลังจาก log in
     */
    function home() {
        $this->pageTitle = 'Welcome ' . $this->Auth->user('username');

        // render หน้า home ตาม user type ที่ login เข้ามา
        $prefix = $this->Auth->user('prefix');
        if ($prefix == ITS_PREFIX) {
            $this->render('its/its_home');
        } elseif ($prefix == CUST_PREFIX) {
            $this->Customer->id = $this->Auth->user('customer_id');
            $customer_name = $this->Customer->field('name');
            $this->Site->id = $this->Auth->user('site_id');
            $site_name = $this->Site->field('name');
            $this->Session->write('Vmi.header', ' for ' . $customer_name);
            $this->Session->write('Vmi.site_name', $site_name);
            $this->render('customers/cust_home');
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $this->Supplier->id = $this->Auth->user('supplier_id');
            $supplier_name = $this->Supplier->field('name');
            $this->Session->write('Vmi.header', ' for ' . $supplier_name);
            $this->render('suppliers/supplier_home');
        }
    }

    function popup_search() {
        parent::popup_search();
        $this->set('update', 'userHistory');
        $this->set('action', 'history_display/');
        $this->set('showCaption', false);
        $this->set('popupWidth', 380);
        $this->set('popupHeight', 320);
    }

    /**
     * สำหรับ Customer head office user เปลี่ยน site ที่ต้องการดู
     */
    function change_view_site() {
        $this->Session->write('Auth.User.site_id', $this->data['view_site']);

        // ลบ parameter ที่เก็บไว้ใน session ของหน้า display ออก
        $this->Session->delete('CustStocksIn');
        $this->Session->delete('CustStocksOut');
        $this->Session->delete('CustReserves');
        $this->Session->delete('CustProductSites');
        $this->Session->delete('CustStockOutReturns');
        $this->Session->delete('CustReturns');
        $this->Session->delete('CustReturnToSuppliers');
        $this->redirect($this->referer());
    }

    /**
     * ใช้ในหน้า home ของ its, Vendor และ Customer
     * Alert ระดับสินค้าที่เหลือในลูกค้าที่ต่ำกว่า max และ min
     */
    function cust_stock_alerts() {
        $customers = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));
        $prefix = $this->Auth->user('prefix');
        if ($prefix == CUST_PREFIX) {
            // ถ้าเป็น vendor เข้ามาดูหน้า home ลูกค้า แสดงเฉพาะ vendor นั้น
            if ($this->Session->read('Auth.User.Extend.from_supplier')) {
                $this->data = $this->Customer->findSupplierStockAlert($this->Auth->user('site_id'), $this->Session->read('Auth.User.supplier_id'));
            } else {
                $this->data = $this->Customer->findSupplierStockAlert($this->Auth->user('site_id'));
            }

            $this->render('dashboard/cust_supplier_inventories');
        } elseif ($prefix == SUPPLIER_PREFIX) {
            $this->data = $this->Customer->findCustStockAlert($customers, $prefix, $this->Auth->user('supplier_id'));
            $this->render('dashboard/cust_inventories');
        } elseif ($prefix == ITS_PREFIX) {
            $this->data = $this->Customer->findCustStockAlert($customers, $prefix);
            $this->render('dashboard/cust_inventories');
        }
    }

    /**
     * ใช้ในหน้า home ของ Customer
     * Alert ระดับสินค้าที่เหลือในลูกค้าที่ต่ำกว่า max และ min
     */
    function cust_inventories($site_id = null) {
        // ถ้าเป็น Vendor หรือ ITS ดูที่หน้า home ของตัวเองแล้ว link เข้ามาต้องส่ง site id เข้ามาด้วย แต่ถ้าเป็น หน้า home ของ Customer เอง ดึงจาก session
        $site_id = ($site_id == null? $this->Auth->user('site_id'): $site_id);
        $this->set('site_id', $site_id);
        $this->Site->id = $site_id;
        $customer_id = $this->Site->field('customer_id');

        $this->paginate['CustProductSite']['conditions'] = array(
                'or' => array(
                        array('CustProductSite.current_stock <= CustProductSite.min_stock'),
                        array('CustProductSite.current_stock < CustProductSite.max_stock'),
                        array('CustProductSite.current_stock > CustProductSite.max_stock')
                ),
                'site_id' => $site_id,
//                'CustProductSite.supplier_id' => $this->CustomerSupplier->listSupplierByCustomerId($customer_id, array('has_cust_inventory' => true)),
                'discontinued' => false,
        );

        // ถ้ามาจาก supplier filter เฉพาะ product ของ supplier นี้เท่านั้น
        if ($this->Session->read('Auth.User.Extend.from_supplier') == true || $this->Auth->user('prefix') == SUPPLIER_PREFIX) {
            $this->paginate['CustProductSite']['conditions']['CustProductSite.supplier_id'] = $this->Auth->user('supplier_id');
            $this->paginate['CustProductSite']['conditions']['CustProductSite.dispatch_from'] = SUPPLIER_PREFIX;

        } elseif ($this->Auth->user('prefix') == ITS_PREFIX) {
            // ถ้าเป็น ITS ดูมาจากหน้า Home ของตัวเอง แสดงเฉพาะของ ITS
            $this->paginate['CustProductSite']['conditions']['CustProductSite.dispatch_from'] = ITS_PREFIX;
        } elseif ($this->Auth->user('prefix') == CUST_PREFIX) {
            $this->paginate['CustProductSite']['conditions']['CustProductSite.supplier_id'] = $this->CustomerSupplier->listSupplierByCustomerId($customer_id, array('has_cust_inventory' => true));
        }

        // เรียงลำดับจาก น้อยกว่า min_stock มาก่อน แล้วน้อยกว่า max_stock
        $this->paginate['CustProductSite']['order'] = array('(CustProductSite.current_stock <= CustProductSite.min_stock) + (CustProductSite.current_stock < CustProductSite.max_stock) desc');
        $this->paginate['CustProductSite']['contain'] = array('Site', 'Customer', 'Product' => array('part_no', 'supplier_part_no', 'title', 'text'));
        parent::display('CustProductSite');
        $this->_paging('CustProductSite', 'LIKE');
        $this->render('customers/cust_inventories');
    }

    /**
     * ถูกเรียกมาจากหน้า home ของ ITS, Vendor
     * @param int $site_id
     */
    function popup_cust_inventories($site_id) {
        $this->layout = 'popup';

        $this->Site->id = $site_id;
        $this->set('popupTitle', $this->Site->field('name') . ' Stock Alert');
        $this->set('popupWidth', '$j(document).width() * .95');

        $this->setAction('cust_inventories', $site_id);
    }

    /**
     * ถูกเรียกมาจากหน้า home ของ Customer
     * @param ไม่มีถ้าเป็น all
     *  dispatch_from => ['its', 'supplier'] (optional)
     *  supplier_id dispatch มาจาก supplier
     *  brand_id (optional)
     */
    function popup_cust_supplier_inventories() {
        $this->layout = 'popup';

        $title = '';
        if (!empty($this->passedArgs['dispatch_from'])) {
            if (!empty($this->passedArgs['brand_id'])) {
                $this->Brand->id = $this->passedArgs['brand_id'];
                $title = $this->Brand->field('name');
            } elseif (!empty($this->passedArgs['supplier_id'])) {
                $this->Supplier->id = $this->passedArgs['supplier_id'];
                $title = $this->Supplier->field('name');
            } else {
                $title =  $this->requestAction('system_preferences/get/company_name');
            }
        } else { // 'ALL'
            $title = 'All';
        }

        $this->set('popupTitle', $title . ' Stock Alert');
        $this->set('popupWidth', '$j(document).width() * .95');

        $this->setAction('cust_supplier_inventories');
    }


    /**
     * ใช้ในหน้า home ของ Customer
     * Alert ระดับสินค้าที่เหลือในลูกค้าที่ต่ำกว่า max และ min
     */
    function cust_supplier_inventories() {
        $this->paginate['CustProductSite']['conditions'] = array(
            'or' => array(
                array('CustProductSite.current_stock <= CustProductSite.min_stock'),
                array('CustProductSite.current_stock < CustProductSite.max_stock'),
                array('CustProductSite.current_stock > CustProductSite.max_stock')
            ),
            'site_id' => $this->Auth->user('site_id'),
            'discontinued' => false
        );

        if (!empty($this->passedArgs['dispatch_from'])) {
            $this->paginate['CustProductSite']['conditions']['dispatch_from'] = $this->passedArgs['dispatch_from'];
            if (!empty($this->passedArgs['brand_id'])) {
                $this->paginate['CustProductSite']['conditions']['brand_id'] = $this->passedArgs['brand_id'];
            } elseif (!empty($this->passedArgs['supplier_id'])) {
                $this->paginate['CustProductSite']['conditions']['CustProductSite.supplier_id'] = $this->passedArgs['supplier_id'];
            }
        }

        // เรียงลำดับจาก น้อยกว่า min_stock มาก่อน แล้วน้อยกว่า max_stock
        $this->paginate['CustProductSite']['order'] = array('(CustProductSite.current_stock <= CustProductSite.min_stock) + (CustProductSite.current_stock < CustProductSite.max_stock) desc');
        $this->paginate['CustProductSite']['contain'] = array('Site', 'Customer', 'Product' => array('part_no', 'supplier_part_no', 'title', 'text'));
        parent::display('CustProductSite');
        $this->_paging('CustProductSite', 'LIKE');
        $this->render('customers/cust_supplier_inventories');
    }

    /**
     * Popup search สำหรับ หน้า Home ของ Customer
     */
    function popup_search_cust_inventories() {
        parent::popup_search();
        $this->set('operands', array('<' => '<', '<=' => '<=', '=' => '=', '>' => '>', '>=' => '>='));
        $this->set('popupWidth', '400');

        $suppliers = $this->CustomerSupplier->listSupplierByCustomerId($this->Auth->user('customer_id'), array('has_cust_inventory' => true));
        $this->set('suppliers', $suppliers);
        $this->set('supplierBrands', $this->Brand->find('list', array('conditions' => array('supplier_id' => array_keys($suppliers)), 'order' => 'name')));

        $itsBrands = $this->CustProductSite->listItsBrandByCustomerId($this->Auth->user('customer_id'));
        $this->set('itsBrands', $this->Brand->find('list', array('conditions' => array('id' => $itsBrands), 'order' => 'name')));

        $this->set('action', 'cust_inventories');
        $this->set('update', 'divCustInventories');
        $this->render('customers/popup_search_cust_inventories');
    }

    function refresh_cust_inventories() {
        $this->layout = 'ajax';
        $this->Session->delete($this->name . '.paging');
        $action = 'users/cust_inventories';
        $this->redirect($action);
    }
}
?>
